<template>
  <div style="height: 100%; width: 100%; overflow-x: auto;">
    <el-form :model="form" label-width="100px" inline>
      <el-form-item label="住院号" prop="hospitalNumber">
        <el-input
            v-model="form.hospitalNumber"
            placeholder="请输入查询的住院号"
            style="width: 160px;"
            clearable
            @clear="clearHospitalNumber"
        />
      </el-form-item>

      <el-form-item label="复查项目" prop="reviewItem">
        <el-select
            v-model="form.reviewItem"
            placeholder="请选择复查项目"
            style="width: 160px;"
        >
          <el-option label="全部" value="全部" />
          <el-option label="甲功" value="甲功" />
          <el-option label="血钙" value="血钙" />
          <el-option label="颈部超声" value="颈部超声" />
          <el-option label="其它" value="其它" />
        </el-select>
      </el-form-item>

      <el-form-item label="预约时间" prop="appointmentTimeRange">
        <el-date-picker
            v-model="form.appointmentTimeRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
            style="width: 300px;"
        />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="fetchData">查询</el-button>
      </el-form-item>
    </el-form>

    <el-table
        :key="tableKey"
        :data="tableData"
        border
        style="width: 100%; margin-top: 10px;"
        :height="tableHeight"
        :row-style="{ height: '50px' }"
        :cell-style="{ padding: '0' }"
    >
      <el-table-column
          v-for="(column, index) in columns"
          :key="index"
          :prop="column.prop"
          :label="column.label"
          :min-width="column.minWidth"
      >
        <template v-slot:default="scope">
          <!-- 处理复查结果列 -->
          <template v-if="column.prop === 'reviewResult'">
            <template v-if="scope.row.reviewResult">
              <el-image
                  :src="scope.row.reviewResult"
                  :preview-src-list="[scope.row.reviewResult]"
                  preview-teleported
                  style="width: 100px; height: 100px;"
                  fit="contain"
              ></el-image>
            </template>
            <template v-else>
              <span>无结果</span>
            </template>
          </template>
          <template v-else>
            <!-- 直接显示处理后的时间（已在数据层格式化） -->
            {{ scope.row[column.prop] }}
          </template>
        </template>
      </el-table-column>
    </el-table>

    <el-row style="margin-top: 10px;">
      <el-col :span="24" style="text-align: right;">
        <el-pagination
            @size-change="sizeChange"
            @current-change="currentChange"
            :current-page="page"
            :page-size="size"
            :page-sizes="[10, 20, 50, 100]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
        ></el-pagination>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { apiClient } from '../api/apiClient.ts'

export default {
  name: 'Fuchaxinxi',
  data() {
    return {
      tableKey: 0,
      form: {
        hospitalNumber: "",
        reviewItem: "全部",
        appointmentTimeRange: ["", ""],
      },
      page: 1,
      size: 10,
      total: 0,
      allData: [], // 存储格式化后的全部数据
      tableData: [], // 当前页数据（已格式化）
      tableHeight: 'calc(100% - 120px)',
      columns: [
        { prop: 'hospitalNumber', label: '住院号', minWidth: '120px' },
        { prop: 'itemName', label: '项目名称', minWidth: '120px' },
        { prop: 'appointmentTime', label: '预约时间', minWidth: '160px' },
        { prop: 'reviewResult', label: '复查结果', minWidth: '160px' }
      ]
    };
  },
  created() {
    this.fetchData();
  },
  methods: {
    // 清空住院号
    clearHospitalNumber() {
      this.form.hospitalNumber = "";
    },

    // 格式化日期为 "YYYY-MM-DD"
    formatDate(time) {
      if (!time) return ''; // 空值处理
      const date = new Date(time); // 解析ISO时间字符串
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份从0开始，补零
      const day = String(date.getDate()).padStart(2, '0'); // 日期补零
      return `${year}-${month}-${day}`;
    },

    // 获取数据并格式化时间
    fetchData() {
      const params = {
        hospitalNumber: this.form.hospitalNumber || "",
        reviewItem: this.form.reviewItem,
        startTime: this.form.appointmentTimeRange?.[0] || "",
        endTime: this.form.appointmentTimeRange?.[1] || ""
      };

      apiClient.get('/patient/fuchaxinxi', { params })
          .then(response => {
            if (response.data.code === 1) {
              // 1. 获取原始数据
              const rawData = response.data.data || [];
              // 2. 遍历数据，格式化每个item的预约时间
              this.allData = rawData.map(item => ({
                ...item, // 复制其他属性
                appointmentTime: this.formatDate(item.appointmentTime) // 格式化时间
              }));
              // 3. 更新总数和当前页数据
              this.total = this.allData.length;
              this.getTableData();
            } else {
              this.$message.error('获取数据失败: ' + (response.data.msg || '未知错误'));
              this.allData = [];
              this.total = 0;
              this.tableData = [];
            }
          })
          .catch(error => {
            console.error('获取复查信息失败:', error);
            this.$message.error('网络请求失败，请稍后重试');
          });
    },

    // 获取当前页数据（直接使用已格式化的allData）
    getTableData() {
      const startIndex = (this.page - 1) * this.size;
      const endIndex = startIndex + this.size;
      this.tableData = this.allData.slice(startIndex, endIndex);
      this.tableKey++; // 触发表格重新渲染
    },

    // 页码大小变化
    sizeChange(newSize) {
      this.size = newSize;
      this.page = 1;
      this.getTableData();
    },

    // 当前页码变化
    currentChange(newPage) {
      this.page = newPage;
      this.getTableData();
    }
  }
};
</script>

<style scoped>
.text-wrap {
  white-space: pre-wrap;
  line-height: 1.5;
  max-height: 120px;
  overflow: auto;
  letter-spacing: normal;
  --characters-per-line: 22;
  width: calc(var(--characters-per-line) * 1ch);
  min-height: 48px;
  display: block;
}
h1 {
  margin-bottom: 20px;
}
</style>